﻿using System;
using System.Data;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Krypton.Toolkit;

namespace 防火墙阻止自定义应用程序
{
    public partial class Form1 : KryptonForm
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void kryptonButton1_Click(object sender, EventArgs e)
        {
            var result = Common.Cmd.Run("netsh.exe", "advfirewall firewall show rule name=all dir=out");
            var ms = Regex.Matches(result, "my_rule_(?<title>\\d{8})");
            long max = 0;
            foreach (Match match in ms)
            {
                var title = match.Groups["title"].Value.TrimStart('0');
                var i = long.Parse(title);
                if (i > max) max = i;
            }

            kryptonTextBox2.Text = max.ToString();
            if (kryptonTextBox3.Text.Length < 5) return;

            try
            {
                var files = Directory.GetFiles(kryptonTextBox3.Text, "*.exe", SearchOption.AllDirectories);
                var dt = new DataTable();
                dt.Columns.Add("序号");
                dt.Columns.Add("路径");
                for (var i = 1; i <= files.Length; i++) dt.Rows.Add(i, Path.GetFullPath(files[i - 1]));

                kryptonDataGridView1.DataSource = dt;
                kryptonDataGridView1.Columns[0].Width = 200;
                kryptonDataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            }
            catch (Exception exception)
            {
                KryptonMessageBox.Show(exception.Message);
            }
        }

        private void kryptonButton2_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.Description = "请选择文件夹";
            folderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer;
            folderBrowserDialog1.ShowNewFolderButton = true;
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                kryptonTextBox3.Text = folderBrowserDialog1.SelectedPath;
        }

        private void kryptonButton3_Click(object sender, EventArgs e)
        {
            var success = long.TryParse(kryptonTextBox2.Text, out var max);
            if (!success) return;

            if (kryptonDataGridView1.DataSource is DataTable dt)
                foreach (DataRow row in dt.Rows)
                {
                    max++;
                    Common.Cmd.Run("netsh.exe",
                        $"advfirewall firewall add rule name=\"my_rule_{max:D8}\" dir=out program=\"{row[1]}\" action=block");
                }

            KryptonMessageBox.Show("OK!");
            kryptonDataGridView1.DataSource = null;
        }
    }
}